#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>

#define COMMAND_COUNT_SIZE 32
#define LEFT "["
#define RIGHT "]"
#define SEP " \t"
#define EXITCODE 44

extern char** environ;
char command_arr[COMMAND_COUNT_SIZE];
char* argv[COMMAND_COUNT_SIZE];


const char* GetUserName()
{
    return getenv("USER");
}

const char* GetHostName()
{
    return getenv("HOSTNAME");
}

const char* GetPath()
{
    return getenv("PWD");
}

void GetCommand()
{
    fgets(command_arr,sizeof(command_arr),stdin);
    command_arr[strlen(command_arr)-1]='\0';
}

void StringSplit()
{
    int pos=0;
    argv[pos++]=strtok(command_arr,SEP);
    while(argv[pos++]=strtok(NULL,SEP));
}

void ProcessReplace()
{
    pid_t id=fork();
    if(id<0)
    {
        perror("fork fail...");
        return;
    }
    else if(id==0)
    {
        //子进程执行
        //execvpe(argv[0],argv,environ);
        execvp(argv[0],argv);
        exit(EXITCODE);//验证程序替换是否出错
    }
    else 
    {
        //主进程执行
        int status;
        pid_t ret=waitpid(id,&status,0);//阻塞等待子进程
        if((status>>8)& 0xFF==EXITCODE)printf("程序替换出错...\n");
    }
}

int main()
{
    while(1)
    {
        //1.打印前缀
        printf(LEFT"%s@%s_%s"RIGHT"$",GetUserName(),GetHostName(),GetPath());
        //2.获取指令
        GetCommand()
        //3.字符串分割
        StringSplit();
        //4.指令检查

        //5.程序替换，执行指令
        ProcessReplace();
    }
    return 0;
}